package com.apexsoft.monitor.mq;

import com.alibaba.fastjson.JSONObject;
import com.apexsoft.front.common.utils.DateUtil;
import com.apexsoft.front.common.utils.SpringContextUtil;
import com.apexsoft.monitor.common.MonitorConstant;
import com.apexsoft.monitor.front.console.log.om.Log;
import com.apexsoft.monitor.front.console.log.service.LogService;
import com.rabbitmq.client.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeoutException;

/**
 * Created by lsj on 2017/10/10.
 */
public class LogMqSubscribe {

    private final static Logger log = LogManager.getRootLogger();
    private final static  String QUEUE_NAME = "appLog";

    public static ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();

    public static void subscribe(){

        log.info("start rabbitmq subscribe.............");
        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost(MonitorConstant.MQ_HOST);
        factory.setPort(MonitorConstant.MQ_PORT);
        factory.setUsername(MonitorConstant.MQ_USERNAME);
        factory.setPassword(MonitorConstant.MQ_PASSWORD);
        Connection connection = null;
        try {
            connection = factory.newConnection();
            Channel channel = connection.createChannel();
            //声明要关注的队列
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            log.info("Customer Waiting Received messages......");
            // 告诉服务器我们需要那个频道的消息，如果频道中有消息，就会执行回调函数handleDelivery
            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                                           AMQP.BasicProperties properties, byte[] body)
                        throws IOException {
                    String message = new String(body, "UTF-8");
                    LogMqSubscribe.queue.add(message);
                    System.out.println("Customer Received '" + message + "'");
                }
            };
            //自动回复队列应答 -- RabbitMQ中的消息确认机制
            channel.basicConsume(QUEUE_NAME, true, consumer);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        } catch (TimeoutException e) {
            log.error(e.getMessage(),e);
        }
    }

}
